<?php
namespace WXAPI\Controller;
//use vendor\autoload.php;
// 加载Composer的自动加载器
//require $_SERVER['HTTP_HOST'] . '/vendor/autoload.php';
require_once './ThinkPHP/Library/Vendor/qiniuyun/autoload.php';
use Qcloud\Cos\Client;
use Think\Controller;
class IdentificationController extends BaseController {

    public function index(){
        $this->display();
    }
    public static $secretId = 'AKIDBGIG6nP0Wu8GIB1mU7ykQ2Z3RmNzoYEs';
    public static $secretKey = 'b0DHC0jHi1DrS1VwEWgeS9j7NWTFoEXg';
    public static $error_code = [
        1=>'服务器内部错误，请再次请求',
        2=>'服务暂不可用，请再次请求',
        3=>'调用的API不存在，请检查请求URL后重新尝试，一般为URL中有非英文字符，如“-”，可手动输入重试',
        4=>'集群超限额，请再次请求',
        6=>'无权限访问该用户数据，创建应用时未勾选相关接口',
        13=>'获取token失败',
        14=>'IAM鉴权失败',
        15=>'应用不存在或者创建失败',
        17=>'每天请求量超限额',
        18=>'QPS超限额',
        19=>'请求总量超限额',
        100=>'无效的access_token参数，token拉取失败',
        110=>'access_token无效，token有效期为30天',
        111=>'access_token无效，token有效期为30天',
        216100=>'请求中包含非法参数，请检查后重新尝试',
        216101=>'缺少必须的参数，请检查参数是否有遗漏',
        216102=>'请求了不支持的服务，请检查调用的url',
        216103=>'请求中某些参数过长，请检查后重新尝试',
        216110=>'appid不存在，请重新核对信息是否为后台应用列表中的appid',
        216200=>'图片为空，请检查后重新尝试',
        216201=>'上传的图片格式错误，现阶段我们支持的图片格式为：PNG、JPG、JPEG、BMP，请进行转码或更换图片',
        216202=>'上传的图片大小错误，现阶段我们支持的图片大小为：base64编码后小于4M，分辨率不高于4096*4096，请重新上传图片',
        216203=>'自定义产品识别服务错误码：上传的图片中包含多个主体，请上传只包含一个主体的产品图片入库',
        216401=>'服务器内部错误，请再次请求',
        216630=>'识别错误，请再次请求',
        216634=>'检测错误，请再次请求',
        216681=>'添加入库的图片已经在库里，完全相同（Base64编码相同）的图片不能重复入库',
        282000=>'服务器内部错误，请再次请求',
        282003=>'请求参数缺失',
        282004=>'请求参数缺失',
        282005=>'处理批量任务时发生部分或全部错误，请根据具体错误码排查',
        282006=>'批量任务处理数量超出限制，请将任务数量减少到10或10以下',
        282100=>'图片压缩转码错误',
        282101=>'长图片切分数量超限',
        282102=>'未检测到图片中识别目标',
        282103=>'图片目标识别错误',
        282110=>'URL参数不存在，请核对URL后再次提交',
        282111=>'URL格式非法，请检查url格式是否符合相应接口的入参要求',
        282112=>'url下载超时，请检查url对应的图床/图片无法下载或链路状况不好，您可以重新尝试一下，如果多次尝试后仍不行，建议更换图片地址',
        282113=>'URL返回无效参数',
        282114=>'URL长度超过1024字节或为0',
        282808=>'request id xxxxx 不存在',
        282809=>'返回结果请求错误（不属于excel或json）',
        282810=>'图像识别错误',
        283300=>'入参格式有误，可检查下图片编码、代码格式是否有误',
        336000=>'服务器内部错误，请再次请求',
        336001=>'入参格式有误，比如缺少必要参数、图片base64编码错误等等，可检查下图片编码、代码格式是否有误'
    ];
    
    public function getAccessToken() {
        $client_id = 'ZVtdrXMqQDYcDUd9j9VFTQcn';
        $client_secret = 'Qbfe5u8u33uVyNDk9JUtmgYbhH3J1lx4';
        
        if(tpCache("AccessToken_baidu")){
            return tpCache("AccessToken_baidu");
        }else{
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=".$client_id."&client_secret=".$client_secret."&grant_type=client_credentials",
                CURLOPT_TIMEOUT => 30,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER  => false,
                CURLOPT_SSL_VERIFYHOST  => false,
                CURLOPT_CUSTOMREQUEST => 'POST',
                
                
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Accept: application/json'
                ),

            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $response_data = json_decode($response, true);
            tpCache("AccessToken_baidu",$response_data['access_token'],$response_data['expires_in']);
            return $response_data['access_token'];
        }
    }
    
    //入库
    /*
    img_path图片地址
    img_brief图片关键字
    store_id 商户ID
    platform_id平台ID
    shelf_number货号
    */
    public function rukuPic($data)
    {   
        // $data = [];
        // $data['img_brief'] = '灭火器';
        // $data['store_id'] = 5385;
        // $data['platform_id'] = 1;
        // $data['shelf_number'] = 1;
        //  $data['img_path'] = 'https://static.ddtwj.com/Public/upload/goods/2024/02-27/65ddaa40b3bda.jpg';
        //AccessToken
        $response = self::getAccessToken();
        $token = $response;
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/add?access_token=' . $token;
        $img = file_get_contents($data['img_path']);
        $img = base64_encode($img);
        // $bodys = array(
        //     'brief' => 1,
        //     'image' => $img,
        //     'sub_lib' => "[appid]"
        // );
        $bodys = array(
            'brief' => $data['img_brief'],
            'image' => $img
        );

        $res = $this->request_post($url, $bodys);
        $res = json_decode($res, true);
        

        if($res['error_code']){
            if($res['error_code']){
                $json_arr = array('status'=>-1,'msg'=>self::$error_code[$res['error_code']]);
                exit(json_encode($json_arr));
            }
            $json_arr = array('status'=>-1,'msg'=>'入库失败');
            exit(json_encode($json_arr));
        }

        $resdata = M('img_identify')->add(['img_path'=>$data['img_path'],'img_brief'=>$data['img_brief'],'store_id'=>$data['store_id'],'platform_id'=>$data['platform_id'],'shelf_number'=>$data['shelf_number'],'addtime'=>time()]);
        if($resdata){
            $json_arr = array('status'=>200,'msg'=>'入库成功');
            exit(json_encode($json_arr));
        }else{
            $json_arr = array('status'=>-1,'msg'=>'入库失败');
            exit(json_encode($json_arr));
        }

    }
    
    //检索
    //$img_path图片地址
    public function cmpPic($img_path)
    {
        //AccessToken
        $response = self::getAccessToken();
        $token = $response;
        $curl = curl_init();
        // $img = file_get_contents($img_path);
        // $img = base64_encode($img_path);

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=".$token,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => http_build_query(array(
            'image' => $img_path
    )),
            
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        
        $res = json_decode($response, true);

        if($res['error_code']){
            if($res['error_code']){
                if($res['error_code'] == '216203'){
                    $json_arr = array('status'=>-1,'msg'=>'模型提取不到有效的图片特征');
                }else{
                     $json_arr = array('status'=>-1,'msg'=>self::$error_code[$res['error_code']]);
                }
                exit(json_encode($json_arr));
            }
            $json_arr = array('status'=>-1,'msg'=>'比对失败');
            exit(json_encode($json_arr));
        }
        if($res['result'] && $res['result'][0]['dishes']){
            $dishes = $res['result'][0]['dishes'];
            $json_arr = array('code'=>1,'msg'=>'比对成功','data'=>$dishes);
        }else{
             $json_arr = array('code'=>1,'msg'=>'比对成功','data'=>$res);
        }

        exit(json_encode($json_arr));
    }
    
    /**
     * 发起http post请求(REST API), 并获取REST请求的结果
     * @param string $url
     * @param string $param
     * @return - http response body if succeeds, else false.
     */
    public function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
    
        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);
    
        return $data;
    }

     //出库
    /*
    img_path图片地址
    img_brief图片关键字
    store_id 商户ID
    platform_id平台ID
    */
    public function deletePic($data)
    {
        //AccessToken
        $response = self::getAccessToken();
        $token = $response;
        $img = file_get_contents($data['img_path']);
        $img = base64_encode($img);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/delete?access_token=" . $token,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            // image 可以通过 $this.getFileBase64Content("C:\fakepath\头像.png") 方法获取
            CURLOPT_POSTFIELDS => http_build_query(array(
            'image' => $img
        )),
    
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        ;
        if($response['error_code']){
            $json_arr = array('status'=>-1,'msg'=>'删除失败');
            exit(json_encode($json_arr));
        }
        $resdata = M('img_identify')->where("img_path = '".$data['img_path']."' and img_brief = '".$data['img_brief']."' and store_id=".$data['store_id']." and platform_id= ".$data['platform_id'])->delete();
        if($resdata){
            $json_arr = array('status'=>200,'msg'=>'删除成功');
            exit(json_encode($json_arr));
        }else{
            $json_arr = array('status'=>-1,'msg'=>'删除失败');
            exit(json_encode($json_arr));
        }

    }
    
    //腾讯云获取签名
    public function tx_getSign(){
        $SecretId = self::$secretId;  # 你的秘钥
        $SecretKey = self::$secretKey;
        $Method = 'GET';  # 方法
        $Cos_Path = '/';  # 路径
        $sign = self::getAuthorization($SecretId, $SecretKey, $Method, $Cos_Path);
        //print_r($sign);
        return $sign;
    }

    //curl请求
    function http_request($url,$headers = array(),$data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //抠图
    public function tx_pic(){
        $sign = self::tx_getSign();
        $authorization = $sign;
        $headers = array('Authorization:'.$authorization);
        $url = 'https://zczm-1251050637.cos.ap-guangzhou.myqcloud.com/?ci-process=GoodsMatting&detect-url='.UrlEncode('https://img.zcool.cn/community/01fafb5c88f8d8a801214168976d43.jpg');
        $data = self::http_request($url,$headers);

        // 将二进制数据转换为图片
        $image = imagecreatefromstring($data);
        $filename = 'Public/nobgpic/image20240416.png'; // 保存的文件名
        imagepng($image, $filename); // 保存为PNG格式

        // 释放内存
        imagedestroy($image);
         
        echo "图片已保存为: " . $filename;
    }
    
    //添加图库
    public function tx_add_pic($path,$goods_id,$customContent,$tags){
        $secretId = self::$secretId;
        $secretKey = self::$secretKey;
        $region = 'ap-guangzhou';
        // $goods_id = '1';
        // $customContent ='测试商品';
        // $tags = '{"name":"测试商品"}';
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId,
                    'secretKey' => $secretKey)));
        try {
            // 添加图库图片 https://cloud.tencent.com/document/product/460/63900
            $result = $cosClient->imageSearchAdd(array(
                'Bucket' => 'zczm-1251050637', 
                'Key' => $path, // ObjectKey
                'EntityId' => $goods_id, // 物品 ID，最多支持64个字符。若 EntityId 已存在，则对其追加图片
                'CustomContent' => $customContent, // 用户自定义的内容，最多支持4096个字符，查询时原样带回
                'Tags' => $tags, // 图片自定义标签，最多不超过10个，json 字符串，格式为 key:value 对
            ));
            // 请求成功
            return true;
        } catch (\Exception $e) {
            // 请求失败
            return false;
        }
    }
    
    //比较图
    public function tx_cmp_pic($path){
        $secretId = self::$secretId;
        $secretKey = self::$secretKey;
        $region = 'ap-guangzhou';
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId,
                    'secretKey' => $secretKey)));
        try {
            // 图片搜索接口 https://cloud.tencent.com/document/product/460/63901
            $result = $cosClient->imageSearch(array(
                'Bucket' => 'zczm-1251050637', 
                'Key' => $path, // ObjectKey
                'MatchThreshold' => 80, // 出参 Score 中，只有超过 MatchThreshold 值的结果才会返回。默认为0
                'Offset' => 0, // 起始序号，默认值为0
                'Limit' => 10, // 返回数量，默认值为10，最大值为100
                'Filter' => '', // 针对入库时提交的 Tags 信息进行条件过滤。支持>、>=、<、<=、=、!=，多个条件之间支持 AND 和 OR 进行连接
            ));
            // 请求成功
            return $result;
        } catch (\Exception $e) {
            // 请求失败
            echo($e);
        }
    }
    
    
     /**
     * php 签名样例
     * @param string $method 请求类型 method
     * @param string $filename 文件名称
     * @return string 签名字符串
     */
    function getAuthorization($secretid, $secretkey, $method, $filename)
    {
        // 获取个人 API 密钥 https://console.qcloud.com/capi
        $SecretId = $secretid;
        $SecretKey = $secretkey;
        // 整理参数
        $queryParams = array();
        $headers = array();
        $method = strtolower($method ? $method : 'head');
        $filename = $filename ? $filename : '/';
        substr($filename, 0, 1) != '/' && ($filename = '/' . $filename);
        // 工具方法
        function getObjectKeys($obj)
        {
            $list = array_keys($obj);
            sort($list);
            return $list;
        }
        function obj2str($obj)
        {
            $list = array();
            $keyList = getObjectKeys($obj);
            $len = count($keyList);
            for ($i = 0; $i < $len; $i++) {
                $key = $keyList[$i];
                $val = isset($obj[$key]) ? $obj[$key] : '';
                $key = strtolower($key);
                $list[] = rawurlencode($key) . '=' . rawurlencode($val);
            }
            return implode('&', $list);
        }
        // 要用到的 Authorization 参数列表
        $qSignAlgorithm = 'sha1';
        $qAk = $SecretId;
        $qSignTime = (string)(time() - 60) . ';' . (string)(time() + 3600);
        $qKeyTime = $qSignTime;
        $qHeaderList = strtolower(implode(';', getObjectKeys($headers)));
        $qUrlParamList = strtolower(implode(';', getObjectKeys($queryParams)));
        // 签名算法说明文档：https://www.qcloud.com/document/product/436/7778
        // 步骤一：计算 SignKey
        $signKey = hash_hmac("sha1", $qKeyTime, $SecretKey);
        // 步骤二：构成 FormatString
        $formatString = implode("\n", array(strtolower($method), $filename, obj2str($queryParams), obj2str($headers), ''));
        // 步骤三：计算 StringToSign
        $stringToSign = implode("\n", array('sha1', $qSignTime, sha1($formatString), ''));
        // 步骤四：计算 Signature
        $qSignature = hash_hmac('sha1', $stringToSign, $signKey);
        // 步骤五：构造 Authorization
        $authorization = implode('&', array(
            'q-sign-algorithm=' . $qSignAlgorithm,
            'q-ak=' . $qAk,
            'q-sign-time=' . $qSignTime,
            'q-key-time=' . $qKeyTime,
            'q-header-list=' . $qHeaderList,
            'q-url-param-list=' . $qUrlParamList,
            'q-signature=' . $qSignature
        ));
        return $authorization;
    }
    
    //上传到存储桶
    //$image,$goods_id,$customContent,$tags
    //$type 0默认添加到图片库 1比较图片
    //$upload_flag 1是网路图片,0本地图片
    public function cos_img($image = '',$goods_id="",$customContent="",$tags="",$type=0,$upload_flag=0){
        //获取文件信息
        $file = $_FILES['image'];
        //$file = $image;
        //获取文件后缀
        $file = pathinfo($file);
        
        if($file && $file['extension']){
           $format = $file['extension'];
        }else{
            $format = pathinfo($image, PATHINFO_EXTENSION);
        }
           
        //文件名
        $name =str_ireplace('.','',microtime(true));
        // 文件全名
        $file_name=$name.'.'.$format;
        //目录
        $url='pic';
        // 存储地址
        $file_url = $url.'/'.$file_name;
        //上传秘钥等信息
        $secretId = self::$secretId;
        $secretKey = self::$secretKey;
        //地域节点
        $region = 'ap-guangzhou';
        //实例化链接
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey
                )
            )
        );

        //上传文件
        try {
            //存储桶名称 格式：BucketName-APPID
            $bucket = "zczm-1251050637";
            //上传文件的临时路径
            $srcPath = $file['filename'];
            if($upload_flag){
                $srcPath = $image;
            }
            $file = fopen($srcPath, 'rb');
            if ($file) {
                $result = $cosClient->Upload(
                    $bucket = $bucket,
                    $key = $file_url,
                    $body = $file);
            }
            // $goods_id = '1';
            // $customContent ='测试商品';
            // $tags = '{"name":"测试商品"}';
            $picname = str_ireplace('.','',microtime(true));
            $kou_pic = self::tx_kou_pic(trim($file_url,'/'),$picname);
            if($kou_pic){
                if($type){
                    $result_pic = self::tx_cmp_pic('/pic/'.$picname.'.jpg');
                }else{
                    $result_pic = self::tx_add_pic('/pic/'.$picname.'.jpg',$goods_id,$customContent,$tags);
                }
            }
            
            //trim($file_url,'/') 上传后的目录地址
           exit(json_encode(['code'=>200,'msg'=>'提交成功','data'=>$result_pic]));
        } catch (\Exception $e) {
            exit(json_encode(['code'=>200,'msg'=>$e->getMessage()]));
        }
    }
    
    //上传到存储桶
    //$image,$goods_id,$customContent,$tags
    //$type 0默认添加到图片库 1比较图片
    //$upload_flag 1是网路图片,0本地图片
    public function cos_admin_img($image = '',$goods_id="",$customContent="",$tags="",$type=0,$upload_flag=0){
        //获取文件信息
        $file = $_FILES['image'];
        //$file = $image;
        //获取文件后缀
        $file = pathinfo($file);
        
        if($file && $file['extension']){
            $format = $file['extension'];
        }else{
            $format = pathinfo($image, PATHINFO_EXTENSION);
        }
        
        //文件名
        $name =str_ireplace('.','',microtime(true));
        // 文件全名
        $file_name=$name.'.'.$format;
        //目录
        $url='pic';
        // 存储地址
        $file_url = $url.'/'.$file_name;
        //上传秘钥等信息
        $secretId = self::$secretId;
        $secretKey = self::$secretKey;
        //地域节点
        $region = 'ap-guangzhou';
        //实例化链接
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey
                )
            )
            );
        
        //上传文件
        try {
            //存储桶名称 格式：BucketName-APPID
            $bucket = "zczm-1251050637";
            //上传文件的临时路径
            $srcPath = $file['filename'];
            if($upload_flag){
                $srcPath = $image;
            }
            $file = fopen($srcPath, 'rb');
            if ($file) {
                $result = $cosClient->Upload(
                    $bucket = $bucket,
                    $key = $file_url,
                    $body = $file);
            }
            // $goods_id = '1';
            // $customContent ='测试商品';
            // $tags = '{"name":"测试商品"}';
            $picname = str_ireplace('.','',microtime(true));
            $kou_pic = self::tx_kou_pic(trim($file_url,'/'),$picname);
            if($kou_pic){
                if($type){
                    $result_pic = self::tx_cmp_pic('/pic/'.$picname.'.jpg');
                }else{
                    $result_pic = self::tx_add_pic('/pic/'.$picname.'.jpg',$goods_id,$customContent,$tags);
                }
            }
            print_r('111');
            //trim($file_url,'/') 上传后的目录地址
            return (json_encode(['code'=>200,'msg'=>'提交成功','data'=>$result_pic]));
        } catch (\Exception $e) {
            print_r('222');
            return (json_encode(['code'=>200,'msg'=>$e->getMessage()]));
        }
    }
    
    //抠图
    public function tx_kou_pic($path,$picname){
        $secretId = self::$secretId;
        $secretKey = self::$secretKey;
        $region = 'ap-guangzhou';
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'scheme' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId,
                    'secretKey' => $secretKey)));
        try {
            // --------------------- 4. 云上数据处理 ------------------------------ //
            $ciProcessParams = new \Qcloud\Cos\ImageParamTemplate\CIProcessTransformation('GoodsMatting');
        
            $picOperations = new \Qcloud\Cos\ImageParamTemplate\PicOperationsTransformation();
            $picOperations->setIsPicInfo(1); // is_pic_info
            $picOperations->addRule($ciProcessParams, $picname.'.jpg'); // rules
            $result = $cosClient->ImageProcess(array(
                'Bucket' => 'zczm-1251050637', 
                'Key' => $path,
                'PicOperations' => $picOperations->queryString(),
            ));
            // 请求成功
            // --------------------- 4. 云上数据处理 ------------------------------ //
        } catch (\Exception $e) {
            // 请求失败
            echo($e);
        }
    }
}